package com.tbit.main.service.impl;

import com.tbit.main.constant.AliOssConstant;
import com.tbit.main.dao.huge.ImageDao;
import com.tbit.main.exception.BaseException;
import com.tbit.main.pojo.Image;
import com.tbit.main.pojo.OssConfig;
import com.tbit.main.service.AccountService;
import com.tbit.main.service.ImageService;
import com.tbit.main.service.OssConfigService;
import com.tbit.main.util.FileLoadUtils;
import com.tbit.main.util.OssFileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;


@Service("imageService")
public class ImageServiceImpl implements ImageService {
    @Autowired
    private ImageDao imageDao;
    @Autowired
    private OssConfigService ossConfigService;
    @Autowired
    private AccountService accountService;

    @Override
    public Image getByImageId(String imageId) {
        return imageDao.getByImageId(imageId);
    }

    @Override
    public void add(Image image) {
        imageDao.add(image);
    }

    @Override
    public void del(String imageId) {
        imageDao.del(imageId);
    }

    @Override
    public String addAdvert(Integer account, MultipartFile file) throws Exception {
        String imageId = null;

        if (!FileLoadUtils.checkFileSize(file, 10, "M")) {
            throw new BaseException("Image.tooBig");
        }
        InputStream inputStream = file.getInputStream();
        /**阿里云配置*/
        OssConfig ossConfig = new OssConfig(AliOssConstant.endpoint, AliOssConstant.accessKeyId, AliOssConstant.accessKeySecret,
                AliOssConstant.bucketName);
        /**查询是否存在配置信息*/
        OssConfig ossConfigDB = ossConfigService.getByAccountId(account);
        if (ossConfigDB != null) {
            ossConfig = ossConfigDB;
        }
        //添加图片
        imageId = UUID.randomUUID().toString();

        /**上传阿里云*/
        String fileName = OssFileUtils.uploadByAliYun(inputStream, ossConfig, imageId, file.getContentType(), OssFileUtils.IMAGE);
        return fileName;
    }

}  